package com.sline.servlet.demo1_servlet._04_scope;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/scope/a")
public class aServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset-utf-8");

        /*
        * 三大作用域
        * 名称            类型                  描述
        * request       HttpServletRequest     将数据放在请求作用域中,在一次请求中实现数据共享,比如请求转发
        * session       HttpSession            将数据放在回话作用域中,只要浏览器不关闭,都能共享
        * application   ServletContext         将数据放在当前应用作用域中,应用在服务器启动的时候创建,关闭时销毁
        * */
        Object num_in_request = req.getAttribute("NUM_IN_REQUEST");
        int numInRequest = 1;
        if (num_in_request != null) {
            numInRequest = Integer.valueOf(num_in_request.toString()) + 1;
        }
        req.setAttribute("NUM_IN_REQUEST", numInRequest);

        Object num_in_session = req.getSession().getAttribute("NUM_IN_SESSION");
        int numInSession = 1;
        if (num_in_session != null) {
            numInSession = Integer.valueOf(num_in_session.toString()) + 1;
        }
        req.getSession().setAttribute("NUM_IN_SESSION", numInSession);

        /*
        * Context的三种获取方式
        * 1.在Servlet中,可以直接调用ServletConfig中的getServletContext()
        * 2.可以通过Session获取, Session对象.getServletContext()
        * 3.Servlet3.0中通过req对象获取, HttpRequest对象.getServletContext()
        * */
        ServletContext servletContext = this.getServletContext();
        ServletContext servletContext1 = req.getSession().getServletContext();
        ServletContext servletContext2 = req.getServletContext();
        Object num_in_context = req.getServletContext().getAttribute("NUM_IN_CONTEXT");
        int numInContext = 1;
        if (num_in_context != null) {
            numInContext = Integer.valueOf(num_in_context.toString()) + 1;
        }
        req.getServletContext().setAttribute("NUM_IN_CONTEXT", numInContext);

        req.getRequestDispatcher("/scope/b").forward(req, resp);
    }
}
